package org.neframework.webtest.action.database;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.neframework.webtest.base.BaseController;
import org.neframework.webtest.util.config.Config;
import org.neframework.webtest.util.data.DbTools;
import org.neframework.webtest.util.file.ZipTools;

import com.tmsps.neframework.mvc.annotation.Controller;
import com.tmsps.neframework.mvc.annotation.RequestMapping;
import com.tmsps.neframework.mvc.annotation.ResponseBody;
import com.tmsps.neframework.mvc.plugin.Tip;

@Controller
@RequestMapping("/cp/database")
public class DatabaseController extends BaseController {

	@RequestMapping("/backup_restore")
	public String list() {
		return "/jsp/database/backup_restore.jsp";
	}

	/**
	 * 备份
	 */
	@RequestMapping("/backup")
	@ResponseBody
	public void backup() {
		File backup = DbTools.backup();
		if (backup != null) {
			this.setTipMsg("备份成功!");
		} else {
			this.setTipMsg(false, "备份失败!", Tip.Type.error);
		}
	}

	/**
	 * 备份全部
	 */
	@RequestMapping("/backup_all")
	@ResponseBody
	public void backup_all() {

		// 备份 DB
		File backup = DbTools.backup();
		if (backup == null) {
			this.setTipMsg(false, "备份失败!", Tip.Type.error);
			return;
		}

		// 打包 zip
		File inFile = new File(Config.getConfig().DATA_PATH);
		File outFile = new File(inFile.getParent(), System.currentTimeMillis() + ".zip");
		boolean b = ZipTools.zipFile(inFile, outFile);
		if (b == false) {
			this.setTipMsg(false, "备份失败!打包文件出问题了!", Tip.Type.error);
			return;
		}

		this.setTipMsg("备份成功!", Tip.Type.success);
		result.put("file_zip", outFile.getName());

	}

	/**
	 * 备份全部
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/backup_all_download")
	public void backup_all_download(String file_zip) throws IOException {
		File tmp = new File(Config.getConfig().DATA_PATH);
		File zip = new File(tmp.getParent(), file_zip);

		if (!zip.exists()) {
			try {
				resp.getWriter().println("file not found!");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}// #if

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			resp.setContentType("application/x-msdownload;");
			resp.setHeader("Content-disposition", "attachment; filename=" + new String(file_zip.getBytes("utf-8"), "ISO8859-1"));
			resp.setHeader("Content-Length", zip.length() + "");

			bis = new BufferedInputStream(new FileInputStream(zip));
			bos = new BufferedOutputStream(resp.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead = -1;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}

	}

}
